package m202401.d06;

import java.util.List;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/1/6 10:29
 */
//92. 反转链表 II
public class Q92 {

    public static void main(String[] args) {
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
//        ListNode n4 = new ListNode(4);
//        ListNode n5 = new ListNode(5);
        n1.next = n2;
        n2.next = n3;
//        n3.next = n4;
//        n4.next = n5;
        ListNode listNode = new Q92().reverseBetween(n1, 3, 3);
        System.out.println();
    }

    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode p = head;
        int index = 1;
        ListNode leftPre = null;
        while (index < left) {
            leftPre = p;
            p = p.next;
            index++;
        }
        ListNode reverse = new ListNode(-1);
        ListNode reverseLast = p;
        while (index <= right) {
            ListNode temp = reverse.next;
            reverse.next = p;
            p = p.next;
            reverse.next.next = temp;
            index++;
        }
        reverseLast.next = p;
        if (leftPre != null) {
            leftPre.next = reverse.next;
        } else {
            leftPre = reverse.next;
            return leftPre;
        }
        return head;
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
